import { useRef, useState } from "react";

export function useStreamData(platformCode: string) {
  const [data, setData] = useState("");
  const abortControllerRef = useRef<AbortController | null>(null);

  const cancel = () => {
    abortControllerRef.current?.abort("stop fetch stream");
  };

  const chat = async (
    messages: { role: "user" | "assistant" | "system"; content: string }[]
  ) => {
    setData("");
    abortControllerRef.current = new AbortController();

    const response = await fetch(
      `${process.env.NEXT_PUBLIC_API_URL}/ai/chat/completions`,
      {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          messages,
          stream: true,
          platformCode,
        }),
        signal: abortControllerRef.current.signal,
      }
    );
    if (!response.ok || !response.body) {
      throw response;
    }

    // @ts-expect-error TODO: fix this
    for await (const value of response.body) {
      const chunk = new TextDecoder("utf-8").decode(value);
      const lines = chunk.split("\n\n");
      let text = "";
      for (let line of lines) {
        line = line.slice(5);
        if (!line || line === " [DONE]") break;
        const json = JSON.parse(line);
        const content = json.choices[0].delta.content;
        if (content) {
          text += content;
        }
      }
      setData((previous) => previous + text);
    }
  };

  return { data, chat, cancel };
}
